package org.tp8.sampleapp.view.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.tp8.sampleapp.exc.SampleAppException;
import org.tp8.sampleapp.model.Course;
import org.tp8.sampleapp.service.facade.CourseFacade;
import org.tp8.sampleapp.util.SampleAppLogger;

/**
 * The Class CourseConverter.
 */
@FacesConverter(value = "courseConverter")
@Component
public class CourseConverter extends AbstractConverter {

	/**
	 * The Constant log.
	 */
	private final static SampleAppLogger log = new SampleAppLogger(
			CourseConverter.class);

	/**
	 * The course facade.
	 */
	private CourseFacade courseFacade;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		Course course;
		if (StringUtils.isBlank(value)) {
			return null;
		}

		Long id = Long.valueOf(value);
		try {
			course = getCourseFacade().findOne(id);
		} catch (SampleAppException e) {
			log.error(e);
			course = null;
		}
		return course;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object ovalue) {
		String result;

		if (ovalue instanceof String) {
			String svalue = (String) ovalue;
			if (StringUtils.isBlank(svalue)) {
				result = null;
			} else {
				result = svalue;
			}
		} else if (ovalue instanceof Long) {
			Course course = loadCourse((Long) ovalue);
			result = course.getId().toString();
		} else {
			result = null;
		}

		return result;
	}

	/**
	 * Load course.
	 * 
	 * @param id
	 *            the id
	 * @return the course
	 */
	private Course loadCourse(Long id) {
		Course course;
		try {
			course = getCourseFacade().findOne(id);
		} catch (SampleAppException e) {
			log.error(e);
			course = null;
		}
		return course;
	}

	/**
	 * Gets the course facade.
	 * 
	 * @return the course facade
	 */
	private CourseFacade getCourseFacade() {
		if (courseFacade == null) {
			courseFacade = getApplicationContext().getBean(CourseFacade.class);
		}
		return courseFacade;
	}
}